#include "config.h"
#include "callback.h"
#include "iot2.h"

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"

#include "string.h"
#include "stdio.h"
#include "stdlib.h"

extern SemaphoreHandle_t g_wait_ok_mtx;
extern WAIT_OK g_wait_ok;

extern uint8_t g_is_sub_topic;
extern QueueHandle_t iot_rx_topic_que;

void proc_rx_msg_connected(const char *param, int16_t len)
{
    printf("call proc_rx_msg_connected\n");
}

void proc_rx_msg_ok(const char *param, int16_t len)
{
    printf("call proc_rx_msg_ok\n");
}

int proc_rx_line(char *line_str, int len) 
{
  int ret = 0;
  if (g_wait_ok.is_waiting_ == pdTRUE) {
    //   printf("call proc_rx_line:\n");
    //   for (int i = 0; i < len; i++) {
    //     // printf("%02X ", (uint16_t)lbuf.pbuf[i]);
    //     putchar(line_str[i]);
    //   }
    //   putchar('\n');
    if (strstr(line_str, "OK") != NULL) {
      xSemaphoreTake(g_wait_ok_mtx, portMAX_DELAY);
      g_wait_ok.result_ = 1;
      xSemaphoreGive(g_wait_ok_mtx);
    }
  } else if (g_is_sub_topic == pdTRUE && len > 12) {
    // +MQTTSUBRECV:<LinkID>,<"topic">,<data_length>,data
    if (strstr(line_str, "MQTTSUBRECV") != NULL) {
      // 1.按':'和','进行分割
      char *pos_arr[4] = {0};
      uint16_t i, k = 0;
      for (i = 0; i < len && k < 4; i++) {
        if (line_str[i] == ':') {
          line_str[i] = '\0';
          pos_arr[k++] = &line_str[i] + 1;
        } else if (line_str[i] == ',') {
          line_str[i] = '\0';
          pos_arr[k++] = &line_str[i] + 1;
        }
      }
      // 2.构建TOPIC_BUFFER实体
      TOPIC_BUFFER tbuf;
      memset(&tbuf, 0, sizeof(TOPIC_BUFFER));

      tbuf.link_id_ = atoi(pos_arr[0]); // ':'

      // 解析topic
      volatile int field_len = strlen(pos_arr[1]);  // ','
      if (*(pos_arr[1] + field_len - 1) == '"') {
        field_len--;
      }
      if (*pos_arr[1] == '"') {
        pos_arr[1]++;
        field_len--;
      }
      tbuf.topic_ = pvPortMalloc(field_len + 1);
      memcpy(tbuf.topic_, pos_arr[1], field_len);
      tbuf.topic_[field_len] = '\0';
      
      int data_len = atoi(pos_arr[2]); // ','
      configASSERT(data_len > 0 && data_len < 1024);

      // FIXME:<data>字段的结尾没有'\0',所以不可以采用strlen()获取长度
      field_len = data_len;
      tbuf.data_ = pvPortMalloc(field_len + 1);
      memcpy(tbuf.data_, pos_arr[3], field_len);
      tbuf.data_[field_len] = '\0';

      if (xQueueSend(iot_rx_topic_que, &tbuf, pdMS_TO_TICKS(10)) != pdTRUE) {
        printf("iot_rx_topic_que max!\n");
        if (tbuf.topic_ != NULL) {
          vPortFree(tbuf.topic_);
          tbuf.topic_ = NULL;
        }
        if (tbuf.data_ != NULL) {
          vPortFree(tbuf.data_);
          tbuf.data_ = NULL;
        }
        return -1;
      }
    }
  }
  return ret;
}
